package srv

import (
	"background/model/back/entity"
	"background/model/back/repo"
	"context"
	"fmt"
	"gorm.io/gen/field"
	"time"
)

func NumberTrade(userId int64) string {
	return fmt.Sprintf("%d%d", time.Now().UnixMilli(), userId)
}

func (r CloudUser) CreateOrder(ctx context.Context, userId int64, plan entity.CloudPlan) error {
	count := int32(plan.Period) * plan.Price
	order := entity.CloudOrder{
		ID:     0,
		UserID: 0,
		Number: NumberTrade(userId),
		State:  entity.OrderStateWait,
		Price:  count,
		Pay:    0,
		Note:   "",
		PlanID: plan.ID,
		Period: plan.Period,
	}
	err := r.db.CloudOrder.WithContext(ctx).Create(&order)
	if err != nil {
		return err
	}
	return nil
}
func (r CloudUser) FinishOrder(ctx context.Context, order entity.CloudOrder) error {
	var columns []field.AssignExpr
	columns = append(columns,
		repo.CloudOrder.State.Value(order.State),
	)
	if order.State == entity.OrderStateFinish {
		columns = append(columns,
			repo.CloudOrder.State.Value(order.State),
			repo.CloudOrder.Pay.Value(order.Pay),
			repo.CloudOrder.PayAt.Value(time.Now()),
		)

	}
	r.db.CloudOrder.WithContext(ctx).Where(repo.CloudOrder.ID.Eq(order.ID)).UpdateSimple(
		columns...,
	)
	return nil
}
